<?php
namespace Home\Controller;
use Think\Controller;
class CategoryController extends Controller {
    public function _empty() {
        exit("参数非法");
    }

    public function index(){
        $id = I('id', 0);
        if (!$id) {
            $this->error('分类id非法', U('Index/index'), 2);
        }

        //获取包含子分类的分类信息
        $cate_info = D('category')->getTree($id);
        if(!$cate_info) return $this->error('没有获取到分类信息', U('Index/index'));
        $deep_cate_ids = D('category')->get_deep_children_ids($cate_info);

        $goods_list    = D('goods')->get_category_goods_by_ids($deep_cate_ids);
        $seo           = array(
            'title'       => $cate_info['title'],
            'keywords'    => $cate_info['keywords'],
            'description' => $cate_info['description']
        );

        $this->assign('cate_info', $cate_info);
        $this->assign('seo', $seo);
        $this->assign('goods_list', $goods_list);
        $this->assign('sub_nav', $cate_info['child']);
        $this->display();
    }


    /**
     * 获取导航数据, 将导航数据写入memcache
     */
    private function get_nav() {
        $cate_model = M('category');
        $cate_data = $cate_model->order('cate_path')->select();
        return $this->get_category($cate_data, 0, 2);
    }

    /**
     * 获取导航无限极分类信息
     * @param $data 数据库中存放的分类数据
     * @param $pid  父级id
     * @param $layer 层级，表示要从中遍历出多少层的分类数据 1表示只取一层
     */
    private function get_category($data=array(), $pid=0, $layer)
    {
        $result = array();
        static $loop_count = 0;
        if($loop_count == $layer) return $result;

        foreach($data as $k=>$v) {
            if($v['pid'] == $pid) {
                //只有获取的数据超过一层的时候采取获取下层的数据
                if($layer > 1) {
                    $v[child] = $this->get_category($data, $v['id'], $loop_count+1);
                }
                $result[] = $v;
            }
        }
        $loop_count++;
        return $result;
    }
}